package handler;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import model.Weather;

public class LoRaDataHandle {
	
	String[] Drict={"北风","东北偏北风","东北风","东北偏东风","东风","东南偏东风","东南风","东南偏南风","南风","西南偏南风","西南风",
			"西南偏西风","西风","西北偏西风","西北风","西北偏北风"};
	
	public void Jsonhandle(String result) {
		
		Weather weather = new Weather();
		Date date = new Date();
		SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject json = new JSONObject(result);
        JSONArray list = json.getJSONArray("list");
        
        for(int i=0;i<list.length();i++) {
        	
            long time = list.getJSONObject(i).getLong("$time");
        	String dev = list.getJSONObject(i).getString("deveui");
        	String data = list.getJSONObject(i).getString("data");
        	date.setTime(time);
 
        	weather.put("SO2",Integer.parseInt(data.substring(0,4),16));
        	weather.put("O3",Integer.parseInt(data.substring(4,8),16));
			weather.put("CO",(Integer.parseInt(data.substring(8,12),16))/1000);
			weather.put("NO2",Integer.parseInt(data.substring(12,16),16));
			weather.put("PM25",(Integer.parseInt(data.substring(16,20),16))/10);
			weather.put("PM10",(Integer.parseInt(data.substring(20,24),16))/10);	
			weather.put("Temper",(Integer.parseInt(data.substring(24,28),16))/10);				
			weather.put("Hum",(Integer.parseInt(data.substring(28,32),16))/10);
			weather.put("Press",(Integer.parseInt(data.substring(32,36),16))/10);
			weather.put("Rainfall",(Integer.parseInt(data.substring(36,40),16))/10);
			weather.put("Speed",(Integer.parseInt(data.substring(40,44),16))/10);
			weather.put("Direct",Drict[(int) ((Integer.parseInt(data.substring(44,48),16)+11.25)%360/22.5)]);
			weather.put("SiteID",Character.getNumericValue(dev.charAt(15))+1);
			weather.put("Time",s.format(date));
			weather.save();//数据存入数据库	
			System.out.println("********这次真的把数据写入了数据库哟*********");	
			
        }
        System.out.println("网页返回数据是：\n"+list);
	}
}
